/**
 * Copyright (c) 2017 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
 * @author 张丁方
 * @CreateTime 2017-3-29 15:22:28
 */
package com.hyyt.shopjsp.product.service.imp;

import com.hyyt.shopjsp.product.dao.*;
import com.hyyt.shopjsp.product.pojo.ShopProductType;
import com.hyyt.shopjsp.product.vo.ShopProductTypeVo;
import com.hyyt.shopjsp.product.service.IShopProductTypeService;
import com.hyyt.shopjsp.util.common.ResultMsg;
import com.hyyt.shopjsp.util.common.Utils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import org.apache.log4j.Logger;

@Service
public class ShopProductTypeService implements IShopProductTypeService {
    private static  final Logger logger = Logger.getLogger(IShopProductTypeService.class);

    @Resource
    private ShopProductTypeDAO shopProductTypeDAO;

    @Resource
    private ShopProductParameterDAO shopProductParameterDAO;//商品参数

    @Resource
    private ShopProductAttributeDAO shopProductAttributeDAO;//商品属性

    @Resource
    private ShopSpecificationDao shopSpecificationDAO;//商品规格

    @Resource
    private ShopBrandTypeDAO shopBrandTypeDAO;//品牌

    @Resource
    private ShopProductMeasuringUnitDAO shopProductMeasuringUnitDAO;//计量单位

    /**
     * 保存或更新商品分类对象
     *
     * @param shopProductType CMS_分类表
     * @return 保存后的CMS_分类表
     */
    @Override
    public ResultMsg saveOrUpdateShopProductType(ShopProductType shopProductType) {
        if(Utils.objectIsNotEmpty(shopProductType)){
            if(Utils.objectIsNotEmpty(shopProductType.getProductTypeId())){//修改
                shopProductTypeDAO.update(shopProductType);
            }else{//添加
                shopProductType.setLoadType("2");
                ShopProductType parentCategory = shopProductTypeDAO.load(shopProductType.getParentId());
                if(Utils.objectIsNotEmpty(parentCategory)) {//父节点不为空
                    if (parentCategory.getIsLeaf().compareTo(0) != 0) {
                        parentCategory.setIsLeaf(0);//修改父节点为非子节点
                        shopProductTypeDAO.update(parentCategory);
                    }
                    if(parentCategory.getLevelCode()==2){
                        shopProductType.setLoadType("1");//三级分类下设置为1
                    }
                    shopProductType.setLevelCode(parentCategory.getLevelCode() + 1);
                }else{//父节点为空，当前节点为一级节点
                    shopProductType.setParentId(0);
                    shopProductType.setLevelCode(1);
                }
                shopProductType.setIsLeaf(1);
                shopProductTypeDAO.insert(shopProductType);
            }
            return new ResultMsg(true);
        }else{
            return new ResultMsg(false);
        }
    }

    /**
     * 删除指定ID的CMS_分类表
     *
     * @param productTypeId CMS_分类表ID
     */
    @Override
    public ResultMsg deleteShopProductType(Integer productTypeId) {
        ResultMsg result = new ResultMsg(false);
        if (Utils.objectIsNotEmpty(productTypeId)) {
            //1判断当前ID是否作为父Id，为0表示当前节点为叶子节点，2判断节点下面是否有相关属性（参数，属性，规格）
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("parentId", productTypeId);
            if (shopProductTypeDAO.count(param)==0){
                param.clear();
                param.put("productTypeId", productTypeId);
                int count = shopProductParameterDAO.count(param)+shopProductAttributeDAO.count(param)+shopSpecificationDAO.count(param);
                if (count == 0) {//为0表示该分类下没有相关属性,此时如果该分类下存在的品牌和计量单位可以直接删除
                    shopBrandTypeDAO.delete("deleteByProductId",param);
                    shopProductMeasuringUnitDAO.delete("deleteByProductId",param);
                    ShopProductType shopProductType = shopProductTypeDAO.load(productTypeId);
                    if (Utils.objectIsNotEmpty(shopProductType)) {
                        shopProductTypeDAO.delete(productTypeId); //删除当前分类
                        param.clear();
                        param.put("parentId", shopProductType.getParentId());
                        int count1 = this.countShopProductType(param);
                        //判断此分类是否有兄弟，等于1 即没有兄弟，那么父节点分类即成为叶子节点
                        if (count1 == 0) {
                            ShopProductType parentCategory = shopProductTypeDAO.load(shopProductType.getParentId());
                            parentCategory.setIsLeaf(1);  //改为叶子节点
                            shopProductTypeDAO.update(parentCategory);
                        }
                        result.setSuccess(true);
                    }
                } else {
                    result.setSuccess(false);
                }
            }else{
                result.setSuccess(false);
            }
        }else {
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 删除指定ID集合的SHOP_商品分类
     *
     * @param ids SHOP_商品分类ID集合
    */
    public void deleteShopProductType(Collection<Integer> ids){
        shopProductTypeDAO.batchDelete(ids);
    }

    /**
     * 根据ID加载一个SHOP_商品分类
     *
     * @param id SHOP_商品分类ID
     * @return SHOP_商品分类
     */
    @Override
    public ShopProductType loadShopProductType(Integer id) {
        return shopProductTypeDAO.load(id);
    }

    /**
     * 查询所有的SHOP_商品分类，主要用于分类树的自身维护
    */
    @Override
    public List<ShopProductType> getNodesForManager(Map<String, Object> params) {
        return shopProductTypeDAO.query("getNodesForManager",params);
    }


    /**
     * 查询所有的SHOP_商品分类，主要用于分类树的关联数据的查询
     */
    @Override
    public List<ShopProductType> getNodesForNavigate(Map<String, Object> params) {
        return shopProductTypeDAO.query("getNodesForNavigate",params);
    }

    /**
     * 查询SHOP_商品分类
     *
     * @param params 查询参数，为key-value形式
     * @return SHOP_商品分类集合
     */
    @Override
    public List<ShopProductType> queryShopProductType(Map<String, Object> params) {
        return shopProductTypeDAO.query(params);
    }

    /**
     * 查询SHOP_商品分类
     *
     * @param params   查询参数，没有则传null,分页参数key为“sortColumns”
     * @param startRow 起始行数（不含起始行的数据）
     * @param rowSize  要查询记录数
     * @return SHOP_商品分类集合
     */
    @Override
    public List<ShopProductType> queryShopProductType(Map<String, Object> params, int startRow, int rowSize) {
        return shopProductTypeDAO.query(params, startRow, rowSize);
    }

    /**
     * 自定义查询SHOP_商品分类
     *
     * @param params   查询参数，没有则传null,分页参数key为“sortColumns”
     * @param startRow 起始行数（不含起始行的数据）
     * @param rowSize  要查询记录数
     * @return SHOP_商品分类集合
     */
    @Override
    public List<Map<String, Object>> queryShopProductTypeBySelf(Map<String, Object> params, int startRow, int rowSize) {
        return shopProductTypeDAO.query("query_bySelf",params, startRow, rowSize);
    }

    @Override
    public List<ShopProductTypeVo> queryShopProductTypeVo(Map<String, Object> params, int startRow, int rowSize) {
        return shopProductTypeDAO.query("queryShopProductTypeVo",params, startRow, rowSize);
    }

    /**
     * 统计SHOP_商品分类
     *
     * @param params 查询参数，没有则传null,分页参数key为“sortColumns”
     * @return 结果集记录数
     */
    @Override
    public int countShopProductType(Map<String, Object> params) {
        return shopProductTypeDAO.count(params);
    }

    /**
     * 热销商品分类统计排行
     * @param params
     * @param startRow
     * @param rowSize
     * @return
     */
    @Override
    public List<ShopProductTypeVo> queryHotCategoryStatistics(Map<String, Object> params, int startRow, int rowSize) {
        return shopProductTypeDAO.query("queryHotCategoryStatistics",params, startRow, rowSize);
    }


    /**
     * 导出热销商品分类统计排行excel
     * @param params
     * @return
     */
    @Override
    public List<ShopProductTypeVo> queryHotCategoryStatistics(Map<String, Object> params) {
        return shopProductTypeDAO.query("queryHotCategoryStatistics",params);
    }

    /**
     * 热销商品分类数量
     * @param params
     * @return
     */
    @Override
    public int countHotCategoryStatistics(Map<String, Object> params) {
        return shopProductTypeDAO.count("countHotCategoryStatistics",params);
    }

}